package com.biqee.service.tb.impl;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.biqee.model.TaobaoShopParseResult;
import com.biqee.service.crawler.PageFetcher;
import com.biqee.service.crawler.impl.PageFetcherImpl;
import com.biqee.service.tb.TaobaoCShopRateParseService;
import com.biqee.service.tb.TaobaoCShopParseService;
import com.biqee.util.JSONUtil;
import com.biqee.util.JsoupUtil;

public class TaobaoCShopParseServiceImpl implements TaobaoCShopParseService {
	private static final Logger logger = Logger.getLogger(TaobaoCShopParseServiceImpl.class);
	
	@Override
	public TaobaoShopParseResult parse(Document doc) {
		if(doc == null) {
			throw new RuntimeException("null document!");
		}
		
		try {
			TaobaoShopParseResult result = new TaobaoShopParseResult();
			fillCommonInfo(doc, result);
			fillRate(doc, result);
			
			return result;
		} catch (Exception e) {
			logger.error("parse doc failed. doc: " + doc.baseUri() +
					", cause: ", e);
		}
		
		return null;
	}

	private void fillCommonInfo(Document doc, TaobaoShopParseResult result) {
		Elements divElements = doc.select("div");
		
		Element shopViewElement = null;
		for(Element e : divElements) {
			if("J_shopViewed".equals(e.attr("id"))) {
				shopViewElement = e;
				break;
			}
		}
		if(shopViewElement == null) {
			throw new RuntimeException("shopViewElement not found! doc: " + doc.baseUri());
		}

		String dataStr = shopViewElement.attr("data-value");
		Object dataObj = JSONUtil.jsonToObject(dataStr);

		try {
			String shopId = (String)PropertyUtils.getProperty( dataObj, "shopId" );
			String name = (String)PropertyUtils.getProperty( dataObj, "name" );
			String link = (String)PropertyUtils.getProperty( dataObj, "link" );
			
			result.setShopId(shopId);
			result.setName(name);
			result.setUrl(link);
		} catch (Exception ex) {
			logger.error("parse doc failed. doc: " + doc.baseUri() +
					", cause: ", ex);
		}
				
		Element nickElement = doc.select("span.J_WangWang").first();
		if(nickElement != null) {
			String nick = nickElement.attr("data-nick");
			result.setNick(nick);
		}

		Element mallElement = doc.select("span.mlogo").first();
		if(mallElement != null) {
			result.setMallType();
		} else {
			result.setCommonType();
		}
	}
	
	private void fillRate(Document doc, TaobaoShopParseResult result) {
		String rateUrl = null;
		Elements ahrefElements = doc.select("a");		
		for(Element element : ahrefElements) {
			// <a href="http://rate.taobao.com/user-rate-6ddfc3a194e19cbde7b435ace9240123.htm"
			String href = element.attr("href");
			if(href.contains("rate.taobao.com")) {
				rateUrl = href;
				break;
			}
		}
		
		if(rateUrl == null) {
			throw new RuntimeException("rate url not found. doc: " + doc.baseUri());
		}
		
		String str = pageFetcher.getAsStringWithSpiderHeader(rateUrl, null);
		Document rateDoc = JsoupUtil.createDocument(str);
		if(rateDoc == null) {
			throw new RuntimeException("create doc failed.  url: " + rateUrl);
		} else {
			taobaoCShopRateParseService.parse(rateDoc, result);	
		}
	}
	

	private PageFetcher pageFetcher;
	
	public void setPageFetcher(PageFetcher pageFetcher) {
		this.pageFetcher = pageFetcher;
	}

	private TaobaoCShopRateParseService taobaoCShopRateParseService;

	public void setTaobaoCShopRateParseService(
			TaobaoCShopRateParseService taobaoCShopRateParseService) {
		this.taobaoCShopRateParseService = taobaoCShopRateParseService;
	}

	public static void main(String[] args) {
		String filePath = "D:\\work\\biqee\\test-pages\\taobao\\common\\common-shop.html";
		InputStream in;
		TaobaoShopParseResult result = null;
		TaobaoCShopParseServiceImpl parser = new TaobaoCShopParseServiceImpl();
		PageFetcher pageFetcher = new PageFetcherImpl();
		TaobaoCShopRateParseService taobaoCShopRateParseService = new TaobaoCShopRateParseServiceImpl();
		parser.setTaobaoCShopRateParseService(taobaoCShopRateParseService);
		parser.setPageFetcher(pageFetcher);
		
		try {
			in = new FileInputStream(filePath);			
			Document doc = JsoupUtil.createDocument(in, "gbk", "http://item.taobao.com/item.htm?id=2222538727&traclelog=jubuyoriprice");
			result = parser.parse(doc);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		
		String desc = ToStringBuilder.reflectionToString(result, ToStringStyle.MULTI_LINE_STYLE);
		System.out.println(desc);
	}
}
